//
//  OrderDetailsViewController.m
//  quickBatchManager
//
//  Created by jack on 15/10/9.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "OrderDetailsViewController.h"
#import "TableCell.h"
#import "PrintUtil.h"
@interface OrderDetailsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    UICollectionView *mCollectionView;
    NSArray *datalist;
}
@end

@implementation OrderDetailsViewController
@synthesize bgView,closeBtn;
- (void)viewDidLoad {
    [super viewDidLoad];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _sessionController = [[WSSessionController sharedController]init];
}

- (void)_accessoryDidDisconnect:(NSNotification *)notification{
    
   // [[self navigationController] popViewControllerAnimated:YES];
    
    if (_sessionController != nil) {
        _sessionController = nil;
    }
}


-(void)initUI
{
    self.view.backgroundColor=[UIColor clearColor];
    UIImage *image = bgView.image;
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    bgView.image=image;
    
    [closeBtn bk_whenTapped:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    mCollectionView = [self setupCollectionView];
    [self.view addSubview:mCollectionView];
    
    [_editBtn bk_whenTapped:^{
        _saleOrder.isArchive = NO;
        [_saleOrder updateToDB];
        [self dismissViewControllerAnimated:YES completion:nil];
        if([_delegate respondsToSelector:@selector(deleteOrder:)])
        {
            [_delegate deleteOrder:self];
        }
        
    }];
    
    if(!_isEdit)
    {
        [_editBtn setHidden:YES];
    }
    
    
    [_printBtn bk_whenTapped:^{
       // [self printOrder:_saleOrder andProductList:datalist];
        [PrintUtil printOrder:_saleOrder andControl:_sessionController];
    }];
    
    
    [_sendBtn bk_whenTapped:^{
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeImage;
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:UM_KEY
                                          shareText:nil
                                         shareImage:[ToolUtils snapshot:self.view]
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline]
                                           delegate:nil];
    }];
    
}


-(void)initData
{
    
    _saleOrder = [AppService getSaleOrderByNo:_saleOrder.saleOrderNo];
    
    
    
    NSMutableArray *batchlist=[[NSMutableArray alloc] init];
    [batchlist addObject:[ToolUtils numberToStr:_saleOrder.saleOrderId]];
    
    
    NSMutableArray *tlist=[[NSMutableArray alloc] init];
    NSArray *plist=[SaleOrderInfoModel searchWithWhere:@{@"saleOrderId":batchlist} orderBy:nil groupBy:@"productId" offset:0 count:0];
    
    
    datalist=tlist;
    
    for (SaleOrderInfoModel *data in plist) {
        NSMutableArray *p1=[[NSMutableArray alloc] init];
        TableModel *model=[[TableModel alloc] init];
        model.tableList=p1;
        model.modelTitle=data.product.modelNo;
        model.totalTitle=[NSString stringWithFormat:@"￥ %0.1f元 计：%0.f",[SaleOrderInfoModel sumWithWhere:@"productNumber*price" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}],[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}]];
        model.productNumber = [SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId]}];
        [tlist addObject:model];
        
        
        NSDictionary *colorsizeDic=[AppService getSizeAndColorByModel:data.product.modelNo];
        
        NSArray *sizeList=colorsizeDic[@"size"];
        NSArray *colorList=colorsizeDic[@"color"];
        
        for (int i=0; i<=colorList.count; i++) {
            NSMutableArray *p2=[[NSMutableArray alloc] init];
            [p1 addObject:p2];
            for (int j=0; j<=sizeList.count; j++)
            {
                if(i==0 && j==0)
                {
                    [p2 addObject:@"颜色"];
                }
                else if(i==0)
                {
                    [p2 addObject:[sizeList objectAtIndex:j-1]];
                }
                else if(j==0)
                {
                    [p2 addObject:[colorList objectAtIndex:i-1]];
                }
                else  {
                    [p2 addObject:[ToolUtils numberToStr:[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":batchlist,@"productId":[ToolUtils numberToStr:data.productId],@"sizeName":[sizeList objectAtIndex:j-1],@"colorName":[colorList objectAtIndex:i-1]}]]];
                }
            }
        }
        
    }
    
    
    
    
    
    if(_saleOrder.clientId)
    {
        _clientNameLabel.text = [NSString stringWithFormat:@"客户:%@",_saleOrder.client.clientName];
    }else
    {
        _clientNameLabel.text = [NSString stringWithFormat:@"客户:%@",_saleOrder.clientName];
    }
    
    _dateLabel.text = _saleOrder.date;
    _numberLabel.text = _saleOrder.saleOrderNo;
    _remarkabel.text = [NSString stringWithFormat:@"备注:%@",_saleOrder.remark];
    
    
    _payInfoLabel.text = [NSString stringWithFormat:@"共%d款 出%0.0f件 退%d 总额:%0.1f",datalist.count,_saleOrder.totalNumber,0,_saleOrder.orderPrice];
    if(_saleOrder.isPay)
    {
        _isPayLabel.text = @"已付款";
    }else
    {
        _isPayLabel.text = @"未付款";
    }
    
    
}



/**
 *  根据类型装载展示模式
 *
 */
-(UICollectionView *)setupCollectionView
{
    if(mCollectionView!=nil)
    {
        [mCollectionView removeFromSuperview];
        mCollectionView = nil;
    }
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //  [flowLayout setItemSize:CGSizeMake(250, 0)];//设置cell的尺寸
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);//设置其边界
    flowLayout.footerReferenceSize = CGSizeMake(100, 10);
    flowLayout.minimumLineSpacing = 5;
    flowLayout.minimumInteritemSpacing = 5;
    
    
    //其布局很有意思，当你的cell设置大小后，一行多少个cell，由cell的宽度决定
    mCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(180,CGRectGetMaxY(_clientInfoView.frame)+100,_clientInfoView.frame.size.width,350)collectionViewLayout:flowLayout];
    [mCollectionView registerClass:[ProductTableCell class] forCellWithReuseIdentifier:@"ProductTableCell"];
    mCollectionView.delegate = self;
    mCollectionView.dataSource = self;
    [mCollectionView setBackgroundColor:[UIColor clearColor]];
    //mCollectionView.layer.borderWidth = 1;
    return mCollectionView;
    
}



#pragma mark --collectionView datasource delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(datalist!=nil)
        return [datalist count];
    return 0;
}


// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *reuseIdetify = @"ProductTableCell";
    ProductTableCell  *tableCell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdetify forIndexPath:indexPath];
    [tableCell setData:[datalist objectAtIndex:indexPath.row]];
    
    return tableCell;
    
    
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    TableModel *model=[datalist objectAtIndex:indexPath.row];
    return CGSizeMake(250, (model.tableList.count+2)*35);
}




@end
